from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import messages
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count, Q
from apps.projects.models import Project
from apps.subprojects.models import SubProject
from .models import UserProfile
from .forms import UserCreateForm, UserProfileForm
from .decorators import admin_required
from apps.common.mixins import AdminRequiredMixin


@login_required
def dashboard(request):
    """仪表板首页"""
    # 确保用户有UserProfile，如果没有则创建
    try:
        user_profile = request.user.userprofile
    except UserProfile.DoesNotExist:
        user_profile = UserProfile.objects.create(
            user=request.user,
            role='admin' if (request.user.is_superuser or request.user.is_staff) else 'college',
            college=None  # 二级学院用户需要后续设置学院
        )
    
    # 基础统计数据
    context = {
        'user_profile': user_profile,
    }
    
    if user_profile.is_admin:
        # 管理员看到的统计数据
        from django.db.models import Sum
        
        # 计算预算统计
        total_budget = Project.objects.aggregate(total=Sum('budget'))['total'] or 0
        used_budget = SubProject.objects.aggregate(total=Sum('used_budget'))['total'] or 0
        
        # 用户角色统计
        admin_count = UserProfile.objects.filter(role='admin').count()
        college_count = UserProfile.objects.filter(role='college').count()
        
        context.update({
            'total_projects': Project.objects.count(),
            'total_subprojects': SubProject.objects.count(),
            'total_users': User.objects.count(),
            'total_budget': total_budget,
            'used_budget': used_budget,
            'remaining_budget': total_budget - used_budget,
            'admin_count': admin_count,
            'college_count': college_count,
            'active_count': User.objects.filter(is_active=True).count(),
            'recent_projects': Project.objects.select_related('admin_manager').order_by('-created_at')[:5],
            'recent_subprojects': SubProject.objects.select_related('project', 'created_by').order_by('-created_at')[:5],
            'subproject_status_stats': SubProject.objects.values('status').annotate(count=Count('id')),
        })
        
        # 为项目添加剩余预算计算（通过添加临时属性）
        for project in context['recent_projects']:
            project_used = SubProject.objects.filter(project=project).aggregate(
                total=Sum('used_budget')
            )['total'] or 0
            project._remaining_budget_display = project.budget - project_used
            
    else:
        # 二级学院用户看到的统计数据
        user_subprojects = SubProject.objects.filter(created_by=request.user)
        completed_count = user_subprojects.filter(status='completed').count()
        
        # 计算可用项目的剩余预算
        available_projects = []
        for project in Project.objects.order_by('-created_at')[:10]:
            project_used = SubProject.objects.filter(project=project).aggregate(
                total=Sum('used_budget')
            )['total'] or 0
            project._remaining_budget_display = project.budget - project_used
            available_projects.append(project)
        
        context.update({
            'my_subprojects_count': user_subprojects.count(),
            'my_completed_subprojects': completed_count,
            'my_recent_subprojects': user_subprojects.select_related('project').order_by('-created_at')[:5],
            'available_projects': available_projects,
        })
    
    return render(request, 'dashboard/index.html', context)


class UserListView(AdminRequiredMixin, ListView):
    """用户列表视图 (仅管理员)"""
    model = User
    template_name = 'accounts/user_list.html'
    context_object_name = 'users'
    paginate_by = 20
    
    def get_queryset(self):
        queryset = User.objects.select_related('userprofile').order_by('-date_joined')
        
        # 搜索功能
        search = self.request.GET.get('search')
        if search:
            queryset = queryset.filter(
                Q(username__icontains=search) |
                Q(first_name__icontains=search) |
                Q(email__icontains=search) |
                Q(userprofile__college_name__icontains=search)
            )
        
        # 角色筛选
        role = self.request.GET.get('role')
        if role:
            queryset = queryset.filter(userprofile__role=role)
        
        return queryset
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['search'] = self.request.GET.get('search', '')
        context['role'] = self.request.GET.get('role', '')
        context['role_choices'] = UserProfile.ROLE_CHOICES
        return context


class UserCreateView(AdminRequiredMixin, CreateView):
    """创建用户视图 (仅管理员)"""
    form_class = UserCreateForm
    template_name = 'accounts/user_form.html'
    success_url = reverse_lazy('accounts:user_list')
    
    def form_valid(self, form):
        messages.success(self.request, f'用户 {form.cleaned_data["username"]} 创建成功')
        return super().form_valid(form)
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = '创建用户'
        return context


class UserUpdateView(AdminRequiredMixin, UpdateView):
    """更新用户视图 (仅管理员)"""
    model = User
    fields = ['username', 'first_name', 'email', 'is_active']
    template_name = 'accounts/user_update.html'
    success_url = reverse_lazy('accounts:user_list')
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['profile_form'] = UserProfileForm(instance=self.object.userprofile)
        context['title'] = f'编辑用户 - {self.object.username}'
        return context
    
    def form_valid(self, form):
        # 同时更新用户信息
        profile_form = UserProfileForm(
            self.request.POST, 
            instance=self.object.userprofile
        )
        if profile_form.is_valid():
            profile_form.save()
            messages.success(self.request, f'用户 {self.object.username} 信息更新成功')
        else:
            messages.error(self.request, '用户信息更新失败')
            return self.form_invalid(form)
        
        return super().form_valid(form)


@admin_required
def user_delete(request, pk):
    """删除用户 (仅管理员)"""
    user = get_object_or_404(User, pk=pk)
    
    # 防止删除自己
    if user == request.user:
        messages.error(request, '不能删除自己的账号')
        return redirect('accounts:user_list')
    
    if request.method == 'POST':
        username = user.username
        user.delete()
        messages.success(request, f'用户 {username} 已删除')
        return redirect('accounts:user_list')
    
    return render(request, 'accounts/user_confirm_delete.html', {
        'user_to_delete': user,
        'title': f'删除用户 - {user.username}'
    })


@login_required
def profile_view(request):
    """查看个人信息"""
    return render(request, 'accounts/profile.html', {
        'user_profile': request.user.userprofile,
        'title': '个人信息'
    })


@login_required
def profile_edit(request):
    """编辑个人信息"""
    if request.method == 'POST':
        # 只允许编辑基本信息，不允许修改角色
        user = request.user
        user.first_name = request.POST.get('first_name', '')
        user.email = request.POST.get('email', '')
        
        try:
            user.full_clean()
            user.save()
            messages.success(request, '个人信息更新成功')
            return redirect('accounts:profile')
        except Exception as e:
            messages.error(request, f'更新失败: {str(e)}')
    
    return render(request, 'accounts/profile_edit.html', {
        'user_profile': request.user.userprofile,
        'title': '编辑个人信息'
    })